/*
    设置日志中会使用到的工具：当前返回时间、判断文件是否存在、查找文件路径、创建目录
*/

#ifndef __M_UTIL_H__
#define __M_UTIL_H__

#include <iostream>
#include <string>
#include <sys/stat.h>
#include <ctime>

namespace Log
{
    namespace util
    {
        class Data
        {
        public:
            // 返回当前时间
            static time_t GetNowTime()
            {
                return (time_t)time(nullptr);
            }
        };

        class File
        {
        public:
            // 判断是否存在
            static bool Exist(const std::string &pathname)
            {
                struct stat st;
                return stat(pathname.c_str(), &st) == 0;
            }

            // 查找路径
            static std::string Path(const std::string &pathname)
            {
                size_t pos = pathname.find_last_of("/\\");
                if (pos == pathname.npos)
                    return ".";
                return pathname.substr(0, pos + 1);
            }

            // 创建目录
            static void CreateDirectory(const std::string &pathname)
            {
                // ./abc/bcd/def
                if(Exist(pathname) == true)
                    return;

                size_t pos = 0, idx = 0;

                while (idx < pathname.size())
                {
                    pos = pathname.find_first_of("/\\", idx);
                    if (pos == pathname.npos)
                    {
                        mkdir(pathname.c_str(), 0777);
                        return;
                    }
                    std::string name = pathname.substr(0, pos + 1);
                    if (Exist(name) == true)
                    {
                        idx = pos + 1;
                        continue;
                    }
                    mkdir(name.c_str(), 0777);
                    idx = pos + 1;
                }
            }
        };
    }
}

#endif